using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Text;
using System.IO;
using System.Web.SessionState;
using NetWing.Model;
using NetWing.Bll;
using Omu.ValueInjecter;
using NetWing.BPM.Core;
using NetWing.BPM.Core.Bll;
using NetWing.Common;
using NetWing.Common.Data;
using NetWing.Common.Data.SqlServer;
using System.Data;
using System.Data.Sql;
using System.Data.SqlClient;
using NetWing.Common.Excel;
using NetWing.Common.IO;
using NetWing.Common.IO.DirFile;
using NetWing.Common.Data.Filter;
using NetWing.Common.Entity;
using NetWing.BPM.Core.Bll;
using NetWing.BPM.Core.Model;
using NetWing.BPM.Core.Dal;

namespace NetWing.BPM.Admin.MJOrderDetail.ashx
{
    /// <summary>
    /// 入住手续子表 的摘要说明
    /// </summary>
    public class MJOrderDetailHandler : IHttpHandler, IRequiresSessionState
    {
        public void ProcessRequest(HttpContext context)
        {
            context.Response.ContentType = "text/plain";



            int k;
            var json = HttpContext.Current.Request["json"];
            var rpm = new RequestParamModel<MJOrderDetailModel>(context) { CurrentContext = context };
            if (!string.IsNullOrEmpty(json))
            {
                rpm = JSONhelper.ConvertToObject<RequestParamModel<MJOrderDetailModel>>(json);
                rpm.CurrentContext = context;
            }

            switch (rpm.Action)
            {
                case "add":
                    context.Response.Write(MJOrderDetailBll.Instance.Add(rpm.Entity));
                    break;
                case "edit":
                    MJOrderDetailModel d = new MJOrderDetailModel();
                    d.InjectFrom(rpm.Entity);
                    d.KeyId = rpm.KeyId;
                    context.Response.Write(MJOrderDetailBll.Instance.Update(d));
                    break;
                case "export":
                    //string fields = rpm.fields;
                    string fields = rpm.CurrentContext.Request["fields"];
                    string tablename = TableConvention.Resolve(typeof(MJOrderDetailModel));//得到表名
                    DataTable xlsDt = SqlEasy.ExecuteDataTable("select " + fields + " from " + tablename + "");
                    ExcelHelper.NPIOtoExcel(xlsDt, HttpContext.Current.Server.MapPath("\\upload\\excel\\" + tablename + ".xls"));
                    context.Response.Write("{\"status\":\"ok\",\"filename\":\"" + tablename + ".xls\"}");
                    break;
                case "inport"://从Excel导入到数据库
                    if (context.Request["REQUEST_METHOD"] == "OPTIONS")
                    {
                        context.Response.End();
                    }
                    SaveFile("~/temp/", context);
                    break;
                case "delete":
                    context.Response.Write(MJOrderDetailBll.Instance.Delete(rpm.KeyId));
                    break;
                case "alldel"://2017-04-05新增的功能 批量删除删除结果返回删除条数
                    context.Response.Write(NetWing.Dal.MJOrderDetailDal.Instance.Delete(rpm.KeyIds));
                    break;
                case "tui":
                    string sqlwhere = " 1=1 ";
                    if (!string.IsNullOrEmpty(rpm.Filter))//如果筛选不为空
                    {
                        string str = " and " + FilterTranslator.ToSql(rpm.Filter);
                        sqlwhere = sqlwhere + str;
                    }
                    //TableConvention.Resolve(typeof(MJUserModel)) 转换成表名
                    var pcp = new ProcCustomPage(TableConvention.Resolve(typeof(MJOrderDetailModel)))
                    {
                        PageIndex = rpm.Pageindex,
                        PageSize = rpm.Pagesize,
                        OrderFields = rpm.Sort,
                        WhereString = sqlwhere
                    };
                    int recordCount;
                    DataTable dt = DbUtils.GetPageWithSp(pcp, out recordCount);
                    dt.Columns.Add("tuiserviceId", typeof(int)); //对应的退ID
                    dt.Columns.Add("tuiserviceName", typeof(string));//退对应的科目
                    dt.Columns.Add("tuinote", typeof(string));//退对应的备注
                    dt.Columns.Add("tuimoney", typeof(decimal));//退对应的金额
                    foreach (DataRow dr in dt.Rows)//循环服务明细表
                    {
                        decimal tuimoney = 0;
                        string tuinote = "";
                        string tuiserviceName = "";
                        int tuiserviceId = 0;
                        string note = "";
                        decimal paytotal = 0;

                        int serviceId = int.Parse(dr["serviceId"].ToString());
                        if (serviceId==0)//错误补录如果服务id是0
                        {
                            LogModel log = new LogModel();
                            log.BusinessName = "系统错误";
                            log.OperationIp = PublicMethod.GetClientIP();
                            log.OperationTime = DateTime.Now;
                            log.PrimaryKey = "";
                            log.UserId = int.Parse(SysVisitor.Instance.cookiesUserId);
                            log.TableName = "MJOrderDetail";
                            log.note = "MJOrderDetail表中含有serviceId=0的字段 表KeyId是："+ dr["keyid"].ToString()+ "";
                            log.OperationType = (int)OperationType.Sys;
                            LogDal.Instance.Insert(log);
                        }

                        //得到当前服务dr
                        DataRow ndr = SqlEasy.ExecuteDataRow("SELECT * from MJaccountingSubjects  WHERE KeyId=" + serviceId + "");
                        //利用反射给model赋值
                        MJaccountingSubjectsModel nsjm = Entity.GetModelByDataRow<MJaccountingSubjectsModel>(ndr);
                        //得到对应退的科目模型
                        DataRow tdr = SqlEasy.ExecuteDataRow("SELECT * from MJaccountingSubjects  WHERE KeyId=" + nsjm.reverseSubjects + "");
                        MJaccountingSubjectsModel tsjm = Entity.GetModelByDataRow<MJaccountingSubjectsModel>(tdr);
                        #region 计算收费开始

                        DateTime ndt = DateTime.Now;
                        DateTime adt = DateTime.Parse(dr["add_time"].ToString());//得到开始时间
                        DateTime expdt = DateTime.Parse(dr["exp_time"].ToString());
                        int day = (ndt - expdt).Days;//计算出相差天数 如果小于0说明还剩下多少天 如果大于0说明超出多少天
                        int Month = (ndt.Year - expdt.Year) * 12 + (ndt.Month - expdt.Month);//算出实际相差几个月/m
                        int newMonth = 0;
                        newMonth = Month;
                        //小技巧 两个日历日比较 如果开始日期比结束日期日子大则月份减少一个月
                        if (expdt.Day < ndt.Day)
                        {
                            newMonth = newMonth + 1;
                        }



                        string type = "结清";
                        if (newMonth > 0)
                        {
                            type = "补";
                        }
                        if (newMonth < 0)
                        {
                            type = "退";
                        }

                        if (nsjm.istui == 1)//表明可以退的科目
                        {
                            if (nsjm.theonce == 0)//持续性收费
                            {
                                string n = "" + type + "" + newMonth + "月" + dr["servicename"].ToString() + decimal.Round(newMonth * decimal.Parse(dr["sprice"].ToString()), 2);
                                note = note + n;
                                paytotal = paytotal + decimal.Round(newMonth * decimal.Parse(dr["sprice"].ToString()), 2);
                                //decimal.Round(newMonth * decimal.Parse(dr["sprice"].ToString()), 2)//应退的金额
                                tuimoney = paytotal;
                                tuinote = n;
                                tuiserviceId = tsjm.KeyId;
                                tuiserviceName = tsjm.subjectName;
                            }
                            if (nsjm.theonce == 1)//一次性收费都是必须要退的
                            {
                                string j = "退" + dr["servicename"].ToString() + "：-" + decimal.Round(decimal.Parse(dr["sprice"].ToString()), 2);
                                note = note + j;
                                paytotal = paytotal + decimal.Round(decimal.Parse("-" + dr["sprice"].ToString()), 2);
                                //应退的金额decimal.Round(decimal.Parse(dr["sprice"].ToString()), 2)
                                tuimoney = paytotal;
                                tuinote = j;
                                tuiserviceId = tsjm.KeyId;
                                tuiserviceName = tsjm.subjectName;
                            }
                        }
                        else//假如是不可退的项目：目的是退0元科目还是要显示出来
                        {

                            note = " ";
                            tuimoney = 0;
                            tuinote = " ";
                            tuiserviceId = tsjm.KeyId;
                            tuiserviceName = tsjm.subjectName;
                        }



                        #endregion

                        //更新dt数据
                        dr.BeginEdit();
                        dr["tuimoney"] = tuimoney;
                        //dr["tuinote"] = tuinote;
                        dr["tuinote"] = " ";//退租时客户不需要备注了
                        dr["tuiserviceName"] = tuiserviceName;
                        dr["tuiserviceId"] = tuiserviceId;
                        dr.EndEdit();
                    }

                    //DataTable dta = dt;

                    context.Response.Write(JSONhelper.FormatJSONForEasyuiDataGrid(recordCount, dt));
                    break;

                default:
                    context.Response.Write(MJOrderDetailBll.Instance.GetJson(rpm.Pageindex, rpm.Pagesize, rpm.Filter, rpm.Sort, rpm.Order));
                    break;
            }
        }

        /// <summary>
        /// 文件保存操作
        /// </summary>
        /// <param name="basePath"></param>
        private void SaveFile(string basePath, HttpContext context)
        {
            var name = string.Empty;
            basePath = (basePath.IndexOf("~") > -1) ? context.Server.MapPath(basePath) :
            basePath;
            HttpFileCollection files = context.Request.Files;

            if (!Directory.Exists(basePath))//如果文件夹不存在创建文件夹
                Directory.CreateDirectory(basePath);
            //清空temp文件夹
            DirFileHelper.ClearDirectory(basePath);

            var suffix = files[0].ContentType.Split('/');
            var _suffix = suffix[1].Equals("jpeg", StringComparison.CurrentCultureIgnoreCase) ? "" : suffix[1];
            var _temp = System.Web.HttpContext.Current.Request["name"];

            if (!string.IsNullOrEmpty(_temp))
            {
                name = _temp;
            }
            else
            {
                Random rand = new Random(24 * (int)DateTime.Now.Ticks);
                name = rand.Next() + "." + _suffix;
            }

            var full = basePath + name;
            files[0].SaveAs(full);

            DataTable dt = NPOIHelper.ImportExceltoDt(full);
            string connectionString = SqlEasy.connString;
            SqlBulkCopy sqlbulkcopy = new SqlBulkCopy(connectionString, SqlBulkCopyOptions.UseInternalTransaction);
            sqlbulkcopy.DestinationTableName = TableConvention.Resolve(typeof(MJOrderDetailModel));//数据库中的表名
                                                                                                   //自定义的datatable和数据库的字段进行对应  
                                                                                                   //sqlBC.ColumnMappings.Add("id", "tel");  
                                                                                                   //sqlBC.ColumnMappings.Add("name", "neirong");  
            int k = dt.Rows.Count - 1;                                                                       //注意一个问题，最后一列是字段数
            for (int i = 0; i < (dt.Columns.Count - 1); i++)
            {
                sqlbulkcopy.ColumnMappings.Add(dt.Columns[i].ColumnName.ToString(), dt.Columns[i].ColumnName.ToString());

            }
            var _result = "";
            try
            {
                sqlbulkcopy.WriteToServer(dt);
                _result = "{\"msg\" : \"导入数据库成功!\", \"result\" : " + k + ", \"filename\" : \"" + name + "\"}";
            }
            catch (Exception)
            {
                _result = "{\"msg\" : \"导入失败,可能模板不对，或其他原因，建议导出数据作为模板重新处理。注意导入没有校验数据重复功能。请人工校验数据!\", \"result\" : 0, \"filename\" : \"" + name + "\"}";
                //throw;
            }



            System.Web.HttpContext.Current.Response.Write(_result);

        }

        public bool IsReusable
        {
            get
            {
                return false;
            }
        }
    }
}